import { QueryKey, useMutation, useQuery } from "react-query";
import { Project } from "type/project";
import { cleanObject } from "utils";
import { useHttp } from "./http";
import { useAddConfig, useEditConfig, useDeleteConfig } from "./use-optimistic-options";

export const useProject = (param?: Partial<Project>) => {
  // const { run,  ...result } = useAsync<Project[]>();
  const client = useHttp();
  // const fetchProject = useCallback(
  //   () => client("projects", { data: cleanObject(param || {}) }),
  //   [param, client]
  // );
  // useEffect(() => {
  //   run(fetchProject(), fetchProject);
  // }, [param, fetchProject, run]);

  return useQuery<Project[]>(['projects', param], () => client('projects', { data: cleanObject(param || {}) }))
};

export const useEditProject = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (params: Partial<Project>) =>
      client(`projects/${params.id}`, {
        method: "PATCH",
        data: params,
      }),
    useEditConfig(queryKey)
  )
};

export const useAddProject = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (params: Partial<Project>) =>
      client(`projects`, {
        method: "POST",
        data: params,
      }),
    useAddConfig(queryKey)
  )
};

export const useDeleteProject = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    ({ id }: { id: number }) =>
      client(`projects/${id}`, {
        method: "DELETE",
      }),
    useDeleteConfig(queryKey)
  )
};

export const  useProjectDetail = (id?: number) => {
  const client = useHttp()
  return useQuery(
    ['project', { id }],
    () => client(`projects/${id}`),
    {
      enabled: Boolean(id)
    }
  )
}
